package br.com.post.persistence;

import org.hibernate.Session;
import org.hibernate.Transaction;

import br.com.post.model.Subject;

public class SubjectDao {
	private static SubjectDao instance; 
	/**
	 * Persiste assunto no banco
	 * @param subject
	 */
	public void createSubject(Subject subject) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		session.save(subject);
		tx.commit();
		session.close();
	}
	
	/**
	 * Atualiza o assunto no banco
	 * @param subject
	 */
	public void updateSubject(Subject subject) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		session.merge(subject);
		tx.commit();
		session.close();
	}
	
	/**
	 * Seleciona um assunto no banco de acordo com o id(long)
	 * @param subject_id
	 * @return subject
	 */
	public Subject selectSubject(long subject_id) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		Subject subject = (Subject)session.get(Subject.class,subject_id);
		tx.commit();
		session.close();
		return subject;
	}
	
	/**
	 * Deleta o assunto de acordo com o id, primeiro faz um select
	 * para o hibernate entender, depois remove o assunto selecionado
	 * @param subject_id
	 */
	public void deleteSubject(long subject_id) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		Subject subject = selectSubject(subject_id);
		session.delete(subject);
		tx.commit();
		session.close();
	}

	public static SubjectDao getInstance() {
		if(instance==null)
			instance= new SubjectDao();
		return instance;
	}

	public static void setInstance(SubjectDao instance) {
		SubjectDao.instance = instance;
	}
	
}

